<script setup>
// --- SCRIPT部分完全没有改动，以确保功能100%不变 ---
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import courseService from '@/services/courseService.js';
import resourceService from '@/services/resourceService.js';
import learningProgressService from '@/services/learningProgressService.js';
import { userManager } from "@/utils/user.js";
import { creditService } from '@/services/creditService.js';
import {
  ElMessage, ElLoading, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber,
  ElSelect, ElOption, ElUpload, ElButton, ElIcon, ElCollapse, ElCollapseItem,
  ElEmpty, ElDivider, ElTag, ElImage, ElCard, ElRow, ElCol, ElAvatar, ElSkeleton, ElSkeletonItem
} from 'element-plus';
import {
  Coin,
  User as UserIcon,
  Document,
  Link,
  Plus,
  UploadFilled,
  VideoPlay,
  Download,
  Picture as IconPicture,
  Notebook,
  Picture,
  School,
} from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const courseId = route.params.id;

const courseDetail = ref(null);
const loading = ref(true);
const error = ref(null);
const currentUserId = ref(null);
const hasCourseCreditCertified = ref(false);

const courseResources = ref([]);
const courseProgressPercent = ref(0);


const courseResourcesByChapter = computed(() => {
  const grouped = {};
  courseResources.value.forEach(cr => {
    const chapter = cr.chapter || 0;
    if (!grouped[chapter]) {
      grouped[chapter] = [];
    }
    grouped[chapter].push(cr);
  });

  const sortedKeys = Object.keys(grouped).sort((a, b) => parseInt(a) - parseInt(b));
  const sortedGrouped = {};
  sortedKeys.forEach(key => {
    sortedGrouped[key] = grouped[key];
  });
  return sortedGrouped;
});


const activeChapters = ref(['1']);


const isCourseOwner = computed(() => {
  return courseDetail.value && currentUserId.value && courseDetail.value.teacherId === currentUserId.value;
});


const addExistingResourceDialogVisible = ref(false);
const addExistingResourceForm = ref({
  resourceId: '',
  chapter: 1,
});
const userResourcesOptions = ref([]);
const searchingResources = ref(false);


const openAddExistingResourceDialog = async () => {
  addExistingResourceDialogVisible.value = true;
  addExistingResourceForm.value.resourceId = '';
  await fetchNextChapterNumberForForm(addExistingResourceForm.value);
  await searchUserResources('');
};


const searchUserResources = async (query) => {
  if (!currentUserId.value) {
    ElMessage.warning('未能获取当前用户ID，无法搜索资源。');
    return;
  }
  searchingResources.value = true;
  try {

    const res = await resourceService.getResourcesByPublisherId(currentUserId.value, query);
    if (res.success && res.data) {
      userResourcesOptions.value = res.data;
    } else {
      ElMessage.error(res.message || '获取资源列表失败');
      userResourcesOptions.value = [];
    }
  } catch (err) {
    console.error('搜索用户资源失败:', err);
    ElMessage.error('搜索资源时发生网络错误。');
  } finally {
    searchingResources.value = false;
  }
};


const submitAddExistingResource = async () => {
  if (!addExistingResourceForm.value.resourceId || !addExistingResourceForm.value.chapter) {
    ElMessage.warning('请选择资源并填写章节号。');
    return;
  }
  if (!isCourseOwner.value) {
    ElMessage.error('您无权限执行此操作。');
    return;
  }

  try {
    const payload = {
      resourceId: addExistingResourceForm.value.resourceId,
      chapter: addExistingResourceForm.value.chapter,
      operatorId: currentUserId.value,
    };
    const res = await courseService.addResourceToChapter(courseId, payload);
    if (res.success) {
      ElMessage.success('资源已成功添加到课程章节！');
      addExistingResourceDialogVisible.value = false;
      await fetchCourseDetail();
    } else {
      ElMessage.error(res.message || '添加资源到章节失败。');
    }
  } catch (err) {
    console.error('添加现有资源到章节失败:', err);
    ElMessage.error('网络错误，无法添加资源。');
  }
};


const createNewResourceDialogVisible = ref(false);
const creatingResource = ref(false);
const createNewResourceForm = ref({
  title: '',
  fileList: [],
  file: null,
  credit: 0,
  major: '',
  difficulty: 0,
  chapter: 1,
});


const openCreateNewResourceDialog = async () => {
  createNewResourceDialogVisible.value = true;

  createNewResourceForm.value = {
    title: '', description: '', fileList: [], file: null,
    credit: 0, major: '', difficulty: 0, chapter: 1,
  };
  await fetchNextChapterNumberForForm(createNewResourceForm.value);
};


const handleFileChange = (file, fileList) => {
  createNewResourceForm.value.file = file.raw;
  createNewResourceForm.value.fileList = [file];
};
const handleFileRemove = () => {
  createNewResourceForm.value.file = null;
  createNewResourceForm.value.fileList = [];
};


const submitCreateNewResource = async () => {
  const form = createNewResourceForm.value;
  if (!form.title || !form.file || !form.major || form.chapter <= 0) {
    ElMessage.warning('请填写所有必填项（标题、文件、专业、章节号）。');
    return;
  }
  if (!isCourseOwner.value) {
    ElMessage.error('您无权限执行此操作。');
    return;
  }

  creatingResource.value = true;
  try {
    const formData = new FormData();

    if (form.file) {
      formData.append('file', form.file);
    } else {
      ElMessage.warning('请选择资源文件！');
      creatingResource.value = false;
      return;
    }


    if (form.coverImageFile) {
      formData.append('coverImage', form.coverImageFile);
    }


    const resourceMetadata = {
      title: form.title,
      credit: form.credit,
      major: form.major,
      difficulty: form.difficulty,
      publisherId: currentUserId.value,
    };


    formData.append('resource', new Blob([JSON.stringify(resourceMetadata)], { type: 'application/json' }));


    const resourceCreationResponse = await resourceService.createResource(formData);
    if (!resourceCreationResponse.success || !resourceCreationResponse.data) {
      ElMessage.error(resourceCreationResponse.message || '创建资源失败。');
      creatingResource.value = false;
      return;
    }
    const newResourceId = resourceCreationResponse.data.id;


    const linkPayload = {
      resourceId: newResourceId,
      chapter: form.chapter,
      operatorId: currentUserId.value,
    };
    const linkResponse = await courseService.addResourceToChapter(courseId, linkPayload);

    if (linkResponse.success) {
      ElMessage.success('新资源创建并成功添加到课程章节！');
      createNewResourceDialogVisible.value = false;
      await fetchCourseDetail();
    } else {
      ElMessage.error(linkResponse.message || '关联资源到章节失败。');
    }

  } catch (err) {
    console.error('创建新资源并添加到章节失败:', err);
    if (err.response && err.response.data && err.response.data.message) {
      ElMessage.error(`创建新资源失败: ${err.response.data.message}`);
    } else {
      ElMessage.error('网络错误或服务器无响应，请稍后再试！');
    }
  } finally {
    creatingResource.value = false;
  }
};


const fetchNextChapterNumberForForm = async (formRef) => {
  if (!courseId) return;
  try {
    const res = await courseService.getNextChapterNumber(courseId);
    if (res.success) {
      formRef.chapter = res.data;
    } else {
      ElMessage.warning(res.message || '获取下一个章节号失败，默认为1。');
      formRef.chapter = 1;
    }
  } catch (error) {
    console.error('获取下一个章节号网络错误:', error);
    ElMessage.error('获取章节号时发生网络错误。');
    formRef.chapter = 1;
  }
};


async function fetchCourseDetail() {
  if (!courseId) {
    error.value = '无效的课程ID';
    loading.value = false;
    return;
  }
  loading.value = true;
  try {
    const courseResponse = await courseService.getCourseById(courseId);
    if (courseResponse && courseResponse.success) {
      courseDetail.value = courseResponse.data;
      if (currentUserId.value && courseDetail.value.name) {
        hasCourseCreditCertified.value = await creditService.checkStudentCourseCreditStatus(currentUserId.value, courseDetail.value.name);
      }
    } else {
      throw new Error(courseResponse.message || '课程不存在或已被删除');
    }

    if (currentUserId.value) {
      try {
        const progressResponse = await learningProgressService.getProgress(currentUserId.value, courseId);
        if (progressResponse.success && progressResponse.data) {

          courseProgressPercent.value = progressResponse.data.progressPercent || 0;
        } else {

          courseProgressPercent.value = 0;
        }
      } catch (progressError) {
        console.warn('获取课程学习进度失败:', progressError);
        courseProgressPercent.value = 0;
      }
    }

    const resourcesResponse = await courseService.getCourseFullResources(courseId);
    if (resourcesResponse && resourcesResponse.success && resourcesResponse.data) {
      courseResources.value = resourcesResponse.data;

      if (Object.keys(courseResourcesByChapter.value).length > 0) {

        activeChapters.value = [Object.keys(courseResourcesByChapter.value)[0]];
      }
    } else {
      courseResources.value = [];

    }

  } catch (err) {
    console.error('获取课程详情或资源失败:', err);
    error.value = err.message || '加载课程失败，请稍后重试。';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
}

const getResourceIcon = (type) => {
  switch (type) {
    case 'video': return VideoPlay;
    case 'pdf': return Document;
    case 'image': return IconPicture;
    case 'text': return Document;
    case 'office': return Document;
    default: return Document;
  }
};

const goToResourceDetail = (resourceId, resourceTitle) => {
  if (currentUserId.value && courseId && resourceId) {
    learningProgressService.recordView({
      studentId: currentUserId.value,
      courseId: courseId,
      resourceId: resourceId
    }).then(response => {
      console.log(`学习记录请求已发送，后端响应:`, response);
    }).catch(error => {
      console.error("记录学习进度失败:", error);
    });
  }
  router.push({ name: 'ResourceShow', params: { id: resourceId } });
};

const goToCourseCreditCertification = (courseName) => {
  if (courseName && courseDetail.value) {
    router.push({
      name: 'CourseCreditCertification',
      query: {
        courseName: courseName,
        courseId: courseDetail.value.id,
        courseCredit: courseDetail.value.credit
      }
    });
  } else {
    ElMessage.warning('未能获取到课程名称或详情，无法进行学分认证。');
  }
};
onMounted(async () => {
  currentUserId.value = userManager.getUserId();
  await fetchCourseDetail();
});
</script>

<template>
  <div class="page-background">
    <div class="content-panel" v-loading="loading" element-loading-text="正在加载课程...">
      <div v-if="courseDetail">
        <div class="course-header">
          <div class="header-info">
            <h1 class="course-title">{{ courseDetail.name }}</h1>
            <div class="teacher-info">
              <el-avatar :size="32" :src="courseDetail.teacherAvatar" :icon="UserIcon" />
              <span>由 <strong>{{ courseDetail.teacherUsername || '未知教师' }}</strong> 提供</span>
            </div>
            <p class="course-description">{{ courseDetail.description }}</p>
            <div class="meta-bar">
              <div class="meta-info">
                <span class="meta-item"><el-icon><Coin /></el-icon>学分: <strong>{{ courseDetail.credit || 0 }}</strong></span>
                <span class="meta-item" v-if="courseDetail.school"><el-icon><School /></el-icon>学校: <strong>{{ courseDetail.school }}</strong></span>
                <span class="meta-item" v-if="courseDetail.category"><el-icon><Document /></el-icon>分类: <strong>{{ courseDetail.category }}</strong></span>
                <span class="meta-item" v-if="courseDetail.difficulty"><el-icon><Link /></el-icon>难度: <strong>{{ courseDetail.difficulty }}</strong></span>
              </div>
              <el-tooltip effect="dark" :content="hasCourseCreditCertified ? '您已认证过该课程学分' : (courseProgressPercent < 100 ? '课程学习进度需达到100%方可申请认证' : '点击申请课程学分认证')" placement="top">
                <div class="cert-button-wrapper">
                  <el-button type="primary" @click="goToCourseCreditCertification(courseDetail.name)" :disabled="hasCourseCreditCertified || courseProgressPercent < 100">
                    {{ hasCourseCreditCertified ? '已认证' : '学分认证' }}
                  </el-button>
                </div>
              </el-tooltip>
            </div>
          </div>
          <div class="header-image">
            <el-image :src="courseDetail.image" fit="cover" class="course-cover-image" />
          </div>
        </div>

        <div v-if="isCourseOwner" class="teacher-management-section">
          <h3>教师工具</h3>
          <div class="management-buttons">
            <el-button :icon="Plus" @click="openAddExistingResourceDialog">添加现有资源</el-button>
            <el-button type="primary" :icon="UploadFilled" @click="openCreateNewResourceDialog">创建新资源</el-button>
          </div>
        </div>

        <el-divider><h3>课程内容</h3></el-divider>

        <div class="course-resources-display">
          <el-collapse v-model="activeChapters" accordion v-if="Object.keys(courseResourcesByChapter).length > 0">
            <el-collapse-item v-for="(resources, chapter) in courseResourcesByChapter" :key="chapter" :title="`第 ${chapter} 章`" :name="chapter">
              <ul class="resource-list">
                <li v-for="resource in resources" :key="resource.id" class="resource-item" @click="goToResourceDetail(resource.id, resource.title)">
                  <div class="resource-content">
                    <el-icon class="resource-icon"><component :is="getResourceIcon(resource.category)" /></el-icon>
                    <span class="resource-name">{{ resource.title }}</span>
                  </div>
                  <el-tag size="small" effect="plain" round>{{ resource.major || '通用' }}</el-tag>
                </li>
              </ul>
            </el-collapse-item>
          </el-collapse>
          <el-empty v-else description="该课程暂无任何章节或资源。" />
        </div>
      </div>
      <div v-else-if="!loading" class="empty-state">
        <el-empty description="未能找到该课程的详细信息。" />
      </div>
    </div>

    <el-dialog
        v-model="addExistingResourceDialogVisible"
        title="添加现有资源到章节"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="addExistingResourceForm" label-width="120px">
        <el-form-item label="选择资源" required>
          <el-select
              v-model="addExistingResourceForm.resourceId"
              placeholder="请选择您已发布的资源"
              filterable
              remote
              :remote-method="searchUserResources"
              :loading="searchingResources"
              clearable
          >
            <el-option
                v-for="item in userResourcesOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="章节号" required>
          <el-input-number
              v-model="addExistingResourceForm.chapter"
              :min="1"
              controls-position="right"
              class="align-left-chapter-input" ></el-input-number>
          <el-button
              type="text"
              class="ml-2"
              @click="fetchNextChapterNumberForForm(addExistingResourceForm)"
          >获取下一个章节号</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addExistingResourceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddExistingResource">确认添加</el-button>
      </template>
    </el-dialog>

    <el-dialog
        v-model="createNewResourceDialogVisible"
        title="创建新资源并添加到章节"
        width="700px"
        :close-on-click-modal="false"
    >
      <el-form :model="createNewResourceForm" label-width="120px">
        <el-form-item label="资源标题" required>
          <el-input v-model="createNewResourceForm.title" placeholder="请输入资源标题"></el-input>
        </el-form-item>
        <el-form-item label="资源文件" required>
          <el-upload
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="createNewResourceForm.fileList"
              :limit="1"
              accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.mp4,.webm,.ogg,.png,.jpg,.jpeg,.gif,.txt,.md"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF, DOC, PPT, XLS, MP4, 图片, 文本等常见文件类型，单个文件大小不超过 50MB。
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="学分" required>
          <el-input-number v-model="createNewResourceForm.credit" :min="0" :max="100" class="align-left-chapter-input"></el-input-number>
        </el-form-item>
        <el-form-item label="专业" required>
          <el-input v-model="createNewResourceForm.major" placeholder="例如：计算机科学"></el-input>
        </el-form-item>
        <el-form-item label="难度" required>
          <el-select v-model="createNewResourceForm.difficulty" placeholder="请选择难度">
            <el-option label="简单" :value="0"></el-option>
            <el-option label="中等" :value="1"></el-option>
            <el-option label="困难" :value="2"></el-option>
            <el-option label="高阶" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="章节号" required>
          <el-input-number
              v-model="createNewResourceForm.chapter"
              :min="1"
              controls-position="right" class="align-left-chapter-input"
          ></el-input-number>
          <el-button
              type="text"
              class="ml-2"
              @click="fetchNextChapterNumberForForm(createNewResourceForm)"
          >获取下一个章节号</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createNewResourceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateNewResource" :loading="creatingResource">确认创建并添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.align-left-chapter-input ::v-deep .el-input__inner {text-align: left;-webkit-appearance: none;-moz-appearance: textfield;line-height: 1;}
.page-background { background: linear-gradient(180deg, #f8f9fb 0%, #f4f6f9 100%); min-height: 100vh; padding: 24px; }
.content-panel { max-width: 1100px; margin: 0 auto; background-color: #fff; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); padding: 40px; }
.course-header { display: flex; gap: 48px; margin-bottom: 32px; align-items: center; }
.header-info { flex: 1; display: flex; flex-direction: column; }
.course-title { font-size: 2.2rem; color: #202124; margin: 0 0 12px 0; font-weight: 600; line-height: 1.3; }
.teacher-info { display: flex; align-items: center; gap: 8px; margin-bottom: 16px; color: #5f6368; font-size: 1rem; }
.course-description { font-size: 1rem; color: #5f6368; line-height: 1.7; margin-bottom: 24px; }
.meta-bar { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; flex-wrap: wrap;}
.meta-info { display: flex; flex-wrap: wrap; gap: 12px 24px; font-size: 0.9rem; color: #5f6368; align-items: center;}
.meta-item { display: flex; align-items: center; gap: 8px; }
.meta-item strong { color: #202124; font-weight: 500; }
/* 关键修正：增大图片尺寸 */
.header-image { flex-shrink: 0; width: 340px; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1); aspect-ratio: 4 / 3; }
.course-cover-image { width: 100%; height: 100%; object-fit: cover; transition: transform 0.3s ease; }
.course-cover-image:hover { transform: scale(1.05); }

/* 教师管理区 */
.teacher-management-section { background-color: #f7f8fa; padding: 20px; border-radius: 12px; margin: 32px 0; }
.teacher-management-section h3 { font-size: 1.1rem; font-weight: 500; color: #202124; margin: 0 0 16px 0; }
.management-buttons { display: flex; gap: 12px; }

/* 课程内容区 */
.el-divider { margin: 40px 0; }
.el-divider h3 { font-size: 1.5rem; font-weight: 500; color: #202124; }
.course-resources-display { margin-top: -16px; }
.el-collapse { border-top: 1px solid #e4e7ed; border-bottom: 1px solid #e4e7ed; }
.el-collapse-item :deep(.el-collapse-item__header) { font-size: 1.1rem; font-weight: 500; padding: 12px 0; }
.el-collapse-item :deep(.el-collapse-item__wrap) { border-bottom: none; }
.el-collapse-item :deep(.el-collapse-item__content) { padding: 16px 8px; }
.resource-list { list-style: none; padding: 0; display: flex; flex-direction: column; gap: 8px; }
.resource-item { display: flex; justify-content: space-between; align-items: center; padding: 12px; border-radius: 8px; transition: background-color 0.2s ease; cursor: pointer; }
.resource-item:hover { background-color: #f7f8fa; }
.resource-content { display: flex; align-items: center; gap: 12px; flex-grow: 1; }
.resource-icon { color: var(--el-color-primary); }
.resource-name { font-size: 1rem; color: #303133; }

/* 响应式调整 */
@media (max-width: 992px) {
  .course-header { flex-direction: column-reverse; align-items: stretch; gap: 24px; }
  .header-image { width: 100%; height: auto; aspect-ratio: 16/9; }
}

/* 弹窗部分样式保持默认 */
.el-dialog .el-form-item { margin-bottom: 22px; }
.el-dialog .el-select, .el-dialog .el-input, .el-dialog .el-input-number { width: 100%; }
</style>